package com.hao.hospital.service;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hao.hospital.model.User;
import com.hao.hospital.util.WeiXinUtil;
import com.hao.hospital.weixin.api.WeiXinAPI;
import com.jfinal.aop.Enhancer;
import com.jfinal.core.Controller;
import com.rtmap.utils.http.RestfulTemplate;

import cn.jlook.jfinal.ext3.kit.SqlBuilder;
import javassist.expr.NewArray;

public class WeiXinService extends AbstractService {
	private static WeiXinService me;

	public static WeiXinService me() {
		if (null == me) {
			me = Enhancer.enhance(WeiXinService.class);
		}
		return me;
	}

	/**
	 * 创建菜单
	 * 
	 * @param accessToken
	 * @param menu
	 * @return
	 */
	public int createMenu(String accessToken, String menu) {
		int result = 0;
		String url = WeiXinAPI.CreateMenuURL(accessToken);
		System.out.println(url);
		JSONObject jsonObject = RestfulTemplate.INSTANCE.postForObject(url, menu, JSONObject.class);
		if (jsonObject != null) {
			result = jsonObject.getInteger("errcode");
		}
		return result;
	}

	/**
	 * 获取accessToken
	 * 
	 * @return
	 */
	public String getToken() {
		String url = WeiXinUtil.me().initTokenURl();
		JSONObject jsonObject = RestfulTemplate.INSTANCE.getForObject(url, JSONObject.class);
		if (jsonObject != null) {
			return jsonObject.getString("access_token");
		} else {
			return "返回为null";
		}
	}

	/**
	 * 获取user token
	 * 
	 * @return
	 */
	public Map getUserToken(String code) {
		Map<String, Object> data = new HashMap<String, Object>();
		String url = WeiXinUtil.me().initUserTokenURL(code);
		JSONObject jsonObject = JSON.parseObject(RestfulTemplate.INSTANCE.getForObject(url, String.class));
		if (jsonObject != null) {
			try {
				data.put("access_token", jsonObject.getString("access_token"));
				data.put("expires_in", jsonObject.getInteger("expires_in"));// 7200
				data.put("refresh_token", jsonObject.getString("refresh_token"));
				data.put("openid", jsonObject.getString("openid"));
			} catch (Exception e) {
				data.put("errcode", jsonObject.getInteger("errcode"));
			}
		} else {
			data.put("errcode", 10000);
		}
		return data;
	}

	/**
	 * 获取用户基本信息
	 * 
	 * @param accessToken
	 * @param openid
	 * @return
	 */
	public int getUserInfo(String accessToken, String openid) {
		String url = WeiXinUtil.me().initUserInfoURL(accessToken, openid);
		JSONObject jsonObject = JSON.parseObject(RestfulTemplate.INSTANCE.getForObject(url, String.class));
		if (jsonObject != null) {
			try {
				if (SqlBuilder.from(User.table).where("openid=?").count(openid) == 0) {
					User user = new User();
					user.setOpenid(openid);
					user.setNickname(jsonObject.getString("nickname"));
					user.setHeadimgurl(jsonObject.getString("headimgurl"));
					user.setSex(Integer.parseInt(jsonObject.getString("sex")));
					user.setProvince(jsonObject.getString("province"));
					user.setCity(jsonObject.getString("city"));

					System.out.println("存之前");
					user.save();
					System.out.println("存之后");
					return 0;// 新用户
				} else {
					System.out.println("授权完了");
					return 1;// 老用户
				}
			} catch (Exception e) {
				e.printStackTrace();
				return 2;// 获取失败
			}
		} else {
			return 3;// 请求失败
		}
	}
	//授权之后
	public void afterAuth(int flag, Controller c) {
		switch (flag) {
		case 0:
			System.out.println("这里没跳");
			c.redirect("/main/updateinfo");
			//c.render("../main/register/info.html");
			break;
		case 1:
			String name = SqlBuilder.from(User.table).where("openid=?").find(c.getSessionAttr("openid").toString())
					.get("user_name");
			if (StringUtils.isNotEmpty(name)) {
				c.redirect(c.getSessionAttr("url").toString());
			} else {
				c.redirect("/main/updateinfo");
			}
			break;
		case 2:
			c.renderText("用户信息获取失败");
			break;
		case 3:
			c.renderText("请求失败");
			break;
		default:
			break;
		}
	}
}
